import { Component, OnInit } from '@angular/core';
import { MdlSnackbarService } from '@angular-mdl/core';
import { ConfirmationService, SelectItem, TreeNode, DialogService } from 'primeng/primeng';
import { flyIn } from '../../common/animation/common.animation';
import { ConfigService } from './service/config.service';
import { ConfigDetailComponent } from './config-detail.component';

@Component({
  selector: 'app-config',
  templateUrl: './config.component.html',
  styleUrls: ['./config.component.scss'],
  providers: [ConfigService],
  animations: [flyIn]
})
export class ConfigComponent implements OnInit {
  loading: boolean = true;
  systems: TreeNode[];
  selectedSystem: TreeNode;
  suggestions: TreeNode[];
  suggestion: TreeNode;

  display: boolean = false;
  allItems: any[];
  showItems: any[];
  selectedItem: any;

  cols: any[] = new Array(
    { field: 'seq', header: '序号', width: "60px" },
    { field: 'configName', header: '名称', width: "200px" },
    { field: 'configKey', header: '键', width: "300px" },
    { field: 'configValue', header: '值', width: "" }
  );

  constructor(
    private configService: ConfigService,
    private dialogService: DialogService,
    private mdlSnackbarService: MdlSnackbarService,
    private confirmationService: ConfirmationService) { }

  ngOnInit() {
    this.configService.list().subscribe(data => {
      data.forEach((config, i) => config['seq'] = (i + 1));
      this.allItems = this.showItems = data;
    });
  }


  /** 新增 */
  add($event) {
    const ref = this.dialogService.open(ConfigDetailComponent, {
      header: '新增配置项',
      width: '600px',
      contentStyle: { 'height': '450px', 'padding': '0' },
      data:{}
    });
    ref.onClose.subscribe(data => {
      if (data) {
        this.configService.list().subscribe(data => {
          data.forEach((config, i) => config['seq'] = (i + 1));
          this.allItems = this.showItems = data;
        });
        this.mdlSnackbarService.showToast("系统配置项保存成功！");
      }
    });
  }
  /** 修改 */
  update($event) {
    if (this.selectedItem) {
      const ref = this.dialogService.open(ConfigDetailComponent, {
        header: '编辑配置项',
        width: '600px',
        contentStyle: { 'height': '450px', 'padding': '0' },
        data: {
          'configKey': this.selectedItem['configKey']
        }
      });
      ref.onClose.subscribe(data => {
        if (data) {
          this.ngOnInit();
          this.mdlSnackbarService.showToast("系统配置项保存成功！");
        }
      });
    }
  }
  /** 删除 */
  delete() {
    if (this.selectedItem) {
      this.confirmationService.confirm({
        header: '确认',
        message: '您确定要删除选择的记录吗？',
        accept: () => {
          this.configService.delete(this.selectedItem.configKey).subscribe(d => {
            this.ngOnInit();
            this.mdlSnackbarService.showToast("系统配置项删除成功！");
          });
        }
      })
    }
  }
}
